You create a WebSocket connection in JavaScript by instantiating the WebSocket object with the server URL, then handling connection events like open, message, error, and close through event listeners or callback properties.
Creating a WebSocket connection in JavaScript is straightforward thanks to the built-in WebSocket API provided by browsers and Node.js (via libraries or native support in recent versions). The WebSocket constructor takes the server URL and optional protocols, then automatically initiates the handshake. After creation, you interact with the connection through event handlers that fire when the connection opens, messages arrive, errors occur, or the connection closes. This event-driven model integrates seamlessly with JavaScript's asynchronous nature.
URL parameter: Required. Must start with ws:// (unencrypted) or wss:// (encrypted/TLS). The URL can include path and query parameters .
Protocols parameter: Optional. A string or array of strings specifying subprotocols the client supports (e.g., ['chat', 'superchat']). The server must select one .
Origin restrictions: The browser automatically sends the Origin header based on the page's origin, enforcing same-origin policies unless CORS is configured .
The WebSocket object has several important properties that reflect its current state. The readyState property can be CONNECTING (0), OPEN (1), CLOSING (2), or CLOSED (3). You can check this before sending messages to ensure the connection is active. The bufferedAmount property indicates how many bytes of data are queued but not yet sent, useful for backpressure handling when sending large amounts of data.
Text data: Strings are sent as UTF-8 text frames .
Binary data: Can send ArrayBuffer, Blob (browser), or Buffer (Node.js). Set socket.binaryType to 'arraybuffer' or 'blob' to control received binary format .
JSON: Serialize objects with JSON.stringify() before sending; parse received JSON in message handler .
Streams: For large data, consider chunking or using specialized protocols .
Normal closure: socket.close() closes with normal code 1000 .
Custom close codes: socket.close(1001, 'Going away') sends custom code and reason (must follow WebSocket close code ranges) .
Close event properties: The close event provides code, reason, and wasClean (boolean indicating clean closure) .
Automatic reconnection: Not built-in; you must implement reconnection logic by listening to close events and recreating the socket .
Creating WebSocket connections in JavaScript is simple, but building robust real-time applications requires attention to connection management, error handling, and reconnection logic. The WebSocket API provides the foundation, and libraries like Socket.IO, SockJS, or ws (Node.js) build additional features on top. Whether using raw WebSockets or abstractions, the underlying connection creation follows the same pattern: instantiate, listen, send, and close—a pattern that maps naturally to JavaScript's event-driven architecture.